﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.Data.Activation;

namespace StyleMVVM.DependencyInjection
{
	public sealed class FuncExportActivator : IExportActivator
	{
		private bool cache;
		private object cachedValue;
		private ExportFunction exportFunction;

		public FuncExportActivator(ExportFunction exportFunction)
		{
			this.exportFunction = exportFunction;
		}

		public FuncExportActivator(ExportFunction exportFunction, bool cache)
		{
			this.exportFunction = exportFunction;
			this.cache = cache;
		}

		public IDependencyInjectionContainer Container { get; set; }

		public IActivationService ActivationService { get; set; }

		public object Activate(IInjectionContext injectionContext, [ReadOnlyArray] object[] constructorParams)
		{
			object returnValue = cachedValue;

			if (returnValue == null)
			{
				returnValue = exportFunction(Container, injectionContext, constructorParams);

				if (cache)
				{
					cachedValue = returnValue;
				}
			}

			return returnValue;
		}
	}
}